package com.itheima.commons.autoconfig.template;


import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.itheima.commons.autoconfig.properties.SmsProperties;

public class SmsTemplate {

    private SmsProperties properties;

    public SmsTemplate(SmsProperties properties) {
        this.properties = properties;
    }

    /**
     * 发送短信功能接口
     *
     * @param phoneNum
     * @param templateCode
     * @param code
     * @return
     */
    public Boolean sendMsg(String phoneNum, String templateCode, String code) {

        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou",
                properties.getAccessKey(), properties.getSecret());

        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("SignName", "杭州黑马传智健康");
        request.putQueryParameter("TemplateCode", templateCode);
        request.putQueryParameter("TemplateParam", "{\"code\":\"" + code + "\"}");
        request.putQueryParameter("PhoneNumbers", phoneNum);
        try {
            // {"RequestId":"F8500296-EDD0-519D-9EFF-CAC4541A4C8D","Message":"OK","BizId":"460819338584527898^0","Code":"OK"}
            CommonResponse response = client.getCommonResponse(request);
            if (response.getData().contains("\"Message\":\"OK\"")) {
                return true;
            }
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }

        return false;
    }

}
